<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\TaskRequest;
use App\Models\Task;
use App\Models\DepartCate;
use App\Models\Client;
use App\Models\ClientCar;
use App\Models\TaskComment;
use App\Models\TaskService;
use App\Models\TaskDepart;
use App\Models\ServiceType;
use App\Models\MaintainType;
use App\Repos\TaskRepo;
use App\Services\Wechat;
use App\Services\Num2Cny;
use App\Exports\TaskExport;
use App\Models\TaskProcess;
use Maatwebsite\Excel\Facades\Excel;
use DB;
use App\Models\User;

class TaskController extends Controller
{
    public function index(Request $request)
    {
        $where = $param = [];
        $query = Task::query();
        if($request->status) {
            $where['status'] = (int)$request->status;
        }

        if ($request->keyword) {
            $keyword = $request->keyword;
           
            $query->where('car_num','like','%'.$keyword.'%')
                  ->orWhere('phone','like','%'.$keyword.'%')
                  ->orWhere('client_name','like','%'.$keyword.'%');
           
            
            $param['keyword'] = $request->keyword;
        }
        if($request->worker_id){
            $where['worker_id'] = $request->worker_id;
        }

       

        $clients = Client::all();
        $workers = User::where('role_code',2)->get();
    	$list = $query->with('car','client')->where($where)->orderBy('created_at','desc')->paginate(20);
    	return view('admin.task.index',compact('list','param','workers','clients'));
    }

    public function edit($id)
    {

        $data    = Task::find($id);       
        $clients       = Client::select('id','name')->get();
        $cars = ClientCar::get();
        $servicetypes  = ServiceType::select('id','name')->get();
        $departCates   = DepartCate::select(['id','name'])->get();
        $workers       = User::where('role_code',2)->get();
        $maintainTypes = MaintainType::select('id','name')->get();

        $status_arr['1']   = '待处理';
        $status_arr['50']  = '处理中';
        $status_arr['75']  = '等配件';
        $status_arr['100'] = '已完成';
        $status_arr['200'] = '已评价';

        return view('admin.task.edit',compact('data','servicetypes','clients','departCates','workers','maintainTypes','cars','status_arr'));
    }

    public function show($id)
    {
    	$data = Task::find($id);
        //$wechatInfo = Wechat::getUserInfo($data->openid);
        $process = TaskProcess::where('task_id',$id)->get();
        //$comment = TaskComment::where('task_id',$id)->first();
    	return view('admin.task.show',compact('data','process'));
    }

    public function print($id)
    {
        $data = Task::find($id);
        $total_price = $data->total_money;
        // 应收大写
        $total_price_cny = $total_money_cny = Num2Cny::ParseNumber($data->total_money);
        // 实收大写
        if($data->rate) {
          $total_price = round($data->total_money*$data->rate/100,2);
          $total_price_cny = Num2Cny::ParseNumber($total_price);
        }
        

       
        return view('admin.task.print',compact('data','total_money_cny','total_price_cny','total_price'));
    }

    

    

    public function add()
    {
        $clients       = Client::select('id','name')->get();
        $servicetypes  = ServiceType::select('id','name')->get();
        $departCates   = DepartCate::select(['id','name'])->get();
        $workers       = User::where('role_code',2)->get();
        $maintainTypes = MaintainType::select('id','name')->get();
        return view('admin.task.add',compact('clients','servicetypes','departCates','workers','maintainTypes'));
    }

    public function save(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        // dd($data['is_push']);
        $data['creater'] = session('admin')->username;
        $data['code']    = 'T'.date('YmdHi').session('admin')->id;
        $flag = TaskRepo::save($data);
       

        if($flag['status'] == true ) {
            // 推送
            if($data['is_push']==1) {
                $push['task_id']   = $flag['data']['task_id'];
                $push['worker_id'] = $data['worker_id'];
                $push['client_name'] = $data['client_name'];
                TaskRepo::dispatch($push);    
            }
            
            $rs['status'] = 'success';
            $rs['msg']    = '任务发布成功';
            return redirect('zadmin/task/')->withInput()->with('rs',$rs);    
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs)->withInput();
    }

    public function update(Request $request,$id)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        $flag = TaskRepo::update($data,$id);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg']    = '操作成功';
            return back()->with('rs',$rs);
        }
        return back()->with('rs',$rs);

    }

    
    public function del($user_id)
    {
        $rs['status'] = 'warning';
        if(session('admin')->role_code!=1) {
            $rs['msg']    = '没有操作权限';
            return back()->with('rs',$rs);
        }
        $flag = Task::destroy($user_id);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg']    = '删除成功';
            return redirect('zadmin/task/')->withInput()->with('rs',$rs);
        }
    }

    /**
    * 后台操作订单完成
    */
   public function complete(Request $request)
   {
        $rs['status'] = 'danger';
        $rs['msg'] = '操作失败';
        $data['task_id'] = $request->task_id;       
        $data['creater'] = session('admin')->username;
        $flag = TaskRepo::complete($data);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return redirect('zadmin/task')->with('rs',$rs);
        }
        return redirect('zadmin/task')->with('rs',$rs);

   }

    //导出工单。
    public function taskExport(Request $request)
    {
        $param = [];
        if($request->client_id) {
            $param['client_id'] = (int)$request->client_id;
        }
        return Excel::download(new TaskExport($param), '工单统计.xlsx');   
    }

    //单独添加服务项目
    public function saveService(Request $request)
    {
        $rs['status'] = 'danger';
        
        $data = $request->except('_token');
        $flag = TaskRepo::addService($data);
        if($flag['status']) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs);
    }

    public function delService(Request $request)
    {
        $rs['status'] = 'danger';        
        $data = $request->all();
        //dd($data);
        $flag = TaskRepo::delService($data);
        if($flag['status']) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs);
    }


    //单独添加服务项目
    public function saveDepart(Request $request)
    {
        $rs['status'] = 'danger';
        
        $data = $request->except('_token');
        //dd($data);
        $flag = TaskRepo::addDeprt($data);
        if($flag['status']) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs);
    }

    public function delDepart(Request $request)
    {
        $rs['status'] = 'danger';        
        $data = $request->all();
        //dd($data);
        $flag = TaskRepo::delDepart($data);
        if($flag['status']) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs);
    }

    public function changeStatus(Request $request)
    {
        $rs['status'] = 'danger';        
        $data = $request->all();
        //dd($data);
        $flag = TaskRepo::changeStatus($data);
        if($flag['status']) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return back()->with('rs',$rs);
        }
        $rs['msg'] = $flag['msg'];
        return back()->with('rs',$rs);
    }
}
